#include "../include/head.h"

// typedef struct node_S
// {
//     char subpath[256];
//     struct node_S* front;
//     struct node_S* back; 
// }ClientVirtualPathNode;

// typedef struct 
// {
//     ClientVirtualPathNode* head;
//     ClientVirtualPathNode* tail;
//     int size

// }ClientVirtualPathStack;

ClientVirtualPathStack* ClientVirtualPathStack_init(){ 
    return calloc(1,sizeof(ClientVirtualPathStack));
    
}

int ClientVirtualPathStack_print(ClientVirtualPathStack* p,char* str){
   
    if(p->size == 0)
    {
        memcpy(str, "/", 1);
        return 0;
    }
    ClientVirtualPathNode *cur=p->head;

    for(int i=0;i<p->size;i++){
        memcpy(str, "/", 1);
        str += 1;
        memcpy(str, cur->subpath, strlen(cur->subpath));
        str += strlen(cur->subpath);
        cur = cur->back;
    }
    return 0;
}
int ClientVirtualPathStack_push(ClientVirtualPathStack *stack,char *subpath){
    ClientVirtualPathNode* node=(ClientVirtualPathNode* )calloc(1,sizeof(ClientVirtualPathNode));
    memcpy(node->subpath,subpath,strlen(subpath));
    

    if(stack->size==0) {
        stack->head=node;
        stack->tail=node;
    }else{
        node->front=stack->tail; //新节点指向当前节点的
        stack->tail->back=node;  //当前节点的back指向新节点
        stack->tail=node;        //更新最后节点。
    }
    stack->size++;
    return 0;
}

int ClientVirtualPathStack_pop(ClientVirtualPathStack *stack){
    if(stack->size==0) return 0;
    ClientVirtualPathNode *node=stack->tail; 
     //将stack->tail指向当前双向节点的前一个。
    // 这里有问题
    // stack->tail->front->back=NULL; //将stack->tail指向的双向节点的前一个节点，指向空。
    if(stack->size == 1) {
        stack->head = NULL;
        stack->tail = NULL;
    }
    else
    {
        stack->tail=node->front;
        stack->tail->back = NULL;
    }
    free(node);
    stack->size--;
    return 0;
}

